from sqlalchemy import func, and_

from ...db import models as db
from ...db.util import transaction
from ...exceptions import MissingParameterError
from ..base import BaseProcessor


class TableProcessor(BaseProcessor):
    """积分榜/tables
    @transaction()
    def read(self, *args, **kwargs):
        #leagueid = get_parameter(kwargs, ('leagueID', 'leagueid'))
        leagueid = kwargs.get('leagueID')

        r = self.dbh.query(db.League).filter(db.League.leagueid == leagueid).first()
        print('*'*80)
        print(repr(r))
        print('*'*80)
        if r:
           if  r.type == 0:
               return self.rank(*args, **kwargs)
           elif  r.type == 1:
               return self.cuprank(leagueid)
        return None
        #return self.query(*args, **kwargs)
    """

    def rank_by_group(self, g):
        
        rank = func.rank().over(order_by=db.Table.points.desc()).label('rank')
        q = self.dbh.query(db.Table)\
                    .add_columns(rank).join(db.Team, and_(db.Team.clubid == db.Table.clubid , db.Team.leagueid == db.Table.leagueid)).filter(db.Team.group == g)
        q = q.all()
        return q

    def rank(self, *args, **kwargs):
        """Param

        args:( None )
        kwargs:{ leagueid }
        """
        rank = func.rank().over(order_by=db.Table.points.desc()).label('rank')
        q = self.dbh.query(db.Table)\
                    .add_columns(rank)
        if kwargs:
            q = q.filter_by(**kwargs)
        return q.all()
